﻿#region MIT License
/*

Copyright (C) 2011 by Timothy A. Barela

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/
#endregion

using System;
using Mono.Cecil;
using Mono.Cecil.Cil;

namespace Sharpener
{
	/// <summary>
	/// Finds and replaces callvirt's with call instructions, when callvirt is used for null reference checks.
	/// </summary>
	public class StripCallVirtPass : Pass
	{
		public int CallVirtsReplaced { get; private set; }

		public override string StartingMessage
		{
			get { return "Replacing non virtual callvirt's with call instructions."; }
		}

		public override string ClosingMessage
		{
			get { return string.Format("{0} callvirt's were replaced with call.", CallVirtsReplaced ); }
		}

		public override bool Run( AssemblyDefinition assembly )
		{
			CallVirtsReplaced = 0;

			stripAssembly(assembly);
			
			return CallVirtsReplaced > 0; 
		}

		private void stripAssembly( AssemblyDefinition assembly )
		{
			foreach(ModuleDefinition module in assembly.Modules)
			{
				stripModule(module);
			}
		}

		private void stripModule( ModuleDefinition module )
		{
			foreach(TypeDefinition type in module.Types)
			{
				stripType(type);
			}
		}
		
		private void stripType( TypeDefinition type )
		{
			foreach(MethodDefinition method in type.Methods)
			{
				stripMethod(method);
			}
		}

		private void stripMethod( MethodDefinition method )
		{
			if(!method.HasBody)//apparently some methods dont have bodies o_O
				return;

			var processor = method.Body.GetILProcessor();

			for(int i = 0; i < method.Body.Instructions.Count; i++)
			{
				var instruction = method.Body.Instructions[i];

				if(instruction.OpCode == OpCodes.Callvirt)
				{
					MethodReference callee = instruction.Operand as MethodReference;
					MethodDefinition callee_def = callee.Resolve();

					if(canUseCall(callee_def))
					{
						var newInstruction = processor.Create(OpCodes.Call, callee);
						newInstruction.Offset = instruction.Offset;//not sure if the offset matters or not? it was running fine before...
						processor.Replace(instruction, newInstruction);
						CallVirtsReplaced++;
					}
				}
			}
		}

		private bool canUseCall( MethodDefinition def )
		{
			return def.IsManaged && !def.IsVirtual && !def.IsAbstract;
		}
	}
}